<template>
  <div class="mod-config">
    <el-row :gutter="20">

      <el-col :span="24">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
          <el-form-item label="设备名称">
            <el-input v-model="dataForm.deviceName" placeholder="设备名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="设备id">
            <el-input v-model="dataForm.deviceId" placeholder="设备id" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户名">
            <el-select
              v-model="selectUser"
              filterable
              remote
              clearable
              @change="userChange"
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="searchUserByName"
              :loading="searchUserLoading">
              <el-option
                v-for="item in userPage.userDataList"
                :key="item.userId"
                :label="item.username"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="地区">
            <el-input v-model="dataForm.address" placeholder="地区" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="search()">查询</el-button>
          </el-form-item>
        </el-form>

      </el-col>
    </el-row>

    <div class="mod-menu" :style="{height:mapHeight+'px'} ">
      <el-row style="width: 100%;height: 100%">
        <el-amap vid="amapPro"
                 :amap-manager="amapManager"
                 :zoom="zoom"
                 :events="events"
                 :center="mapCenter"
                 :resizeEnable="resizeEnable"
        >
          <el-amap-marker v-for="(marker,index) in markers"
                          :key="index" :events="marker.events" :position="marker.position"/>
          <el-amap-info-window
            v-if="window"
            :position="window.position"
            :visible="window.visible"
            :content="window.content"
            :offset="window.offset"
            :close-when-click-map="true"
            :is-custom="true"
          >
            <div id="info-window">
              <p>{{ window.name }}</p>
              <p>{{ window.lotDeviceId }}</p>
              <p>{{ window.userName }}</p>
              <p>{{ window.simCode }}</p>
              <p>{{ window.address }}</p>
              <!--            <div class="detail" @click="checkDetail">查看详情</div>-->
            </div>

          </el-amap-info-window>
        </el-amap>
      </el-row>
    </div>
  </div>


</template>

<script>
  import {AMapManager, lazyAMapApiLoaderInstance} from 'vue-amap'

  let amapManager = new AMapManager()
  export default {
    // name: 'deviceMap',
    data () {
      let self = this
      return {
        // ------------高德地图参数开始-----------------
        resizeEnable: true, // 是否监控地图容器尺寸变化
        zoom: 13, // 设置初始化级别
        amapManager,
        events: {
          init (o) {
            lazyAMapApiLoaderInstance.load().then(() => {
              // self.initPage() // 初始化数据self指向this
              self.changeMap() // 绑定鼠标缩放事件
            })
          }
        },
        mapHeight: 600,
        markers: [],
        windows: [],
        window: '',
        deviceDataList: [],
        dataForm: {
          deviceId: '',
          deviceName: '',
          address: ''
        },
        userPage: {
          dataListLoading: false,
          userDataList: [],
          limit: 10,
          page: 1,
          total: 0
        },
        searchUserLoading: false,
        selectUser: '',
        pageIndex: 1,
        pageSize: 10,
        total: 0,
        userForm: {
          mobile: '',
          username: ''
        },
        mapCenter: [121.549792, 29.868388]
      }
    },
    mounted () {
      // this.getDataList()
      this.search()
    },
    methods: {
      checkDetail () {
        alert('点击了查看详情')
      },
      // 获取数据列表
      search () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/device/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 3000,
            'lotDeviceId': this.dataForm.deviceId,
            'userId': this.selectUserId,
            'deviceName': this.dataForm.deviceName,
            'address': this.dataForm.address
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.deviceDataList = data.page.list
            this.total = data.page.totalCount
          } else {
            this.deviceDataList = []
            this.total = 0
          }
          this.initPoint()
          this.dataListLoading = false
        })
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/device/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 3000
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.deviceDataList = data.page.list
            this.$message.success('查询成功，符合条件公共' + data.page.totalCount + '个设备')
          } else {
            this.$message.error('查询失败')

            this.deviceDataList = []
          }
          this.initPoint()
          this.dataListLoading = false
        })
      },
      initPoint () {
        const markers = []
        const windows = []
        const that = this
        AMapUI.loadUI(['overlay/SimpleMarker'], function (SimpleMarker) {
          if (that.deviceDataList.length > 0) {
            that.mapCenter = [that.deviceDataList[0].longitude, that.deviceDataList[0].latitude]
          }
          for (let i = 0; i < that.deviceDataList.length; i++) {
            let device = that.deviceDataList[i]
            markers.push({
              position: [device.longitude, device.latitude],
              events: {
                click () {
                  // 方法：鼠标移动到点标记上，显示相应窗体
                  that.windows.forEach(window => {
                    window.visible = false // 关闭窗体
                  })
                  that.window = that.windows[i]
                  that.$nextTick(() => {
                    that.window.visible = true
                  })
                }
              }
            })
            windows.push({
              position: [device.longitude, device.latitude],
              isCustom: true,
              offset: [115, 55],
              showShadow: false,
              visible: false,
              address: device.address,
              name: device.name,
              userName: device.userName,
              simCode: device.simCode
            })
          }
        })

        this.markers = markers
        this.windows = windows
      },
      // -----------------道德地图开始----------
      initPro () {
        let markers = []
        let _this = this
        let map = _this.amapManager.getMap()
        map.clearMap()
        AMapUI.loadUI(['overlay/SimpleMarker'], function (SimpleMarker) {
          let marker = new SimpleMarker({
            // 定位点的样式
            showPositionPoint: {
              // eslint-disable-next-line eqeqeq
              color: 'rgba(255,255,255,0)',
              // eslint-disable-next-line eqeqeq
              radius: 5
            },
            // 直接设置html(需要以"<"开头并且以">"结尾)
            map: map,
            position: [121.63706380208333, 29.92283908420139]
          })
          markers.push(marker)
        })
      },
      // 绑定高德地图放大缩小map事件
      changeMap () {
        let map = this.amapManager.getMap()
        let that = this
        map.on('zoomchange', () => {
          var zoom = map.getZoom() // 获取当前地图级别
          console.info('当前级别：' + zoom)
          if (zoom >= 10) {
            // this.initPro()
            that.initPoint()
          } else {
            map.clearMap()
          }
        })
      },
      searchUserByName (query) {
        if (query !== '') {
          this.loading = true
          this.userForm.username = query
          this.getAppUserList()
        } else {
          this.userPage.userDataList = []
        }
      },
      userChange (user) {
        console.info(user)
        this.selectUserId = user
      },
      getAppUserList () {
        this.$http({
          url: this.$http.adornUrl('/user/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'username': this.userForm.username
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.userPage.userDataList = data.page.list
            this.userPage.total = data.page.totalCount
          } else {
            this.userPage.userDataList = []
            this.userPage.total = 0
          }
        })
      }
    }
  }
</script>
<style scoped>
  .amap-demo {
    height: 120vh;
  }

  .amap-page-container {
    position: relative;
  }

  #info-window {
    width: 211px;
    height: 146px;
    margin-left: 30px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 4px;
    position: relative;
    overflow: hidden;
  }

  .detail {
    width: 100%;
    height: 24px;
    color: #fff;
    background-color: #1a73e8;
    position: absolute;
    bottom: 0;
    font-size: 12px;
    line-height: 24px;
    text-align: center;
    cursor: pointer;
  }

</style>

